const _ = require("lodash");
const fs = require("fs");
const path = require("path");

// ✅ ESM 支持
const esm = require("esm");
const requireModule = esm(module);

// ✅ 模块导入
const checkAccuracy = requireModule("./utils/checkAccuracy.js");
const { readAllValues } = requireModule("../awakened-potential/helpers/readAllValues.js");
const { getStrategyByName } = require("./strategies/strategyManager");

// ✅ 读取历史开奖数据（澳门）
const allValues = readAllValues("m");

// ✅ 使用策略名
const strategyName = "S6";
const select32Numbers = getStrategyByName(strategyName);

// ✅ 控制窗口大小范围
const MIN_WINDOW = 2;
const MAX_WINDOW = 200;

const testResults = [];

for (let windowSize = MIN_WINDOW; windowSize <= MAX_WINDOW; windowSize++) {
  let correct = 0;
  let maxWrongStreak = 0;
  let currentWrongStreak = 0;
  let wrongStreakList = [];

  const predictResults = [];

  allValues.forEach((item, index) => {
    const temp = allValues.slice(Math.max(0, index - windowSize), index);
    if (temp.length === 0) return;

    const predictNumbers = select32Numbers(temp);
    const isHit = checkAccuracy(predictNumbers, item.number);

    predictResults.push({
      index,
      date: item.time,
      actual: item.number,
      predict: predictNumbers,
      hit: isHit,
    });

    if (isHit) {
      if (currentWrongStreak > 0) wrongStreakList.push(currentWrongStreak);
      correct++;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak++;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }
  });

  if (currentWrongStreak > 0) {
    wrongStreakList.push(currentWrongStreak);
  }

  const total = predictResults.length;
  const accuracy = Number(((correct / total) * 100).toFixed(2));

  testResults.push({
    windowSize,
    accuracy,
    maxWrongStreak,
  });
}

// ✅ 输出最佳结果
const bestAcc = _.maxBy(testResults, "accuracy");
const bestStable = _.minBy(testResults, "maxWrongStreak");

console.log("\n✅ 最佳准确率窗口:");
console.log(bestAcc);

console.log("\n❌ 最小连续错误窗口:");
console.log(bestStable);
